<template>
    <div class="w-screen h-screen overflow-hidden" ref="homeContainer" @contextmenu.prevent="showContextMenu">
        <div class="h-full w-full">
            <div class="mask absolute top-0 left-0 h-full w-full transition-colors"></div>
            <div class="icon-list z-sideBar w-[400px] h-full bg-white/80 absolute left-0 top-0 transition-transform duration-300"
                :class="iconWebVisible ? '' : 'translate-x-[-100%]'" id="leftContainer">
                <SideBar ref="sideBar" class="absolute right-[-64px] top-1/2 -translate-y-2/4"
                    v-model:activeIndex="currentPage" v-model:currentCate="currentCate" @clickAvatar="clickAvatar">
                </SideBar>
                <IconList ref="iconWeb" v-model="iconWebVisible" v-on-click-outside="hideAddIconWeb" @add="addIcon"
                    @edit="editIcon" @addTemplate="addTemplate"></IconList>
            </div>
            <div id="homeContainer" class="transition-transform duration-300 h-full w-full overflow-hidden relative"
                :class="iconWebVisible ? 'translate-x-[204px] pointer-events-none' : ''">
                <Search class="search-comp absolute left-1/2 top-[12vh] -translate-x-2/4 z-30" />
                <ViewList class="pt-[25vh]" ref="viewList" v-model:currentPage="currentPage"
                    v-model:currentCate="currentCate" :addHomepageItem="addHomepageItem" @showItems="showAddIconWeb"
                    @changeActiveIndex="changeActiveIndex"></ViewList>
            </div>
        </div>
    </div>
    <Setting ref="setting"></Setting>
    <SelectMenu></SelectMenu>
    <!-- 小组件弹窗 -->
    <SmallComponent v-if="templateVisible" v-model:templateVisible="templateVisible"
        :currentPage="currentPage" @addHomepage="addHomepage">
    </SmallComponent>
</template>
<script setup lang="ts">
import '@/assets/font/iconfont.css';
import { vOnClickOutside } from '@vueuse/components';
import Search from '@/components/Search.vue';
import ViewList from '@/components/ViewList.vue';
import IconList from '@/components/IconList.vue';
import SideBar from '@/components/SideBar.vue';
import Login from '@/views/Login/index.vue';
import Setting from '@/components/Setting.vue';
import SmallComponent from '@/components/SmallComponent/index.vue'
import { ref, watchEffect, provide, onMounted, onUnmounted } from 'vue';
import { getToken, setToken } from '@/utils/auth';
import loginApi from '@/api/login';
import settingApi from '@/api/setting';
import { ElDialog } from "element-plus";
import {
useUserInfoStore,
useContextMenuStore,
useSettingStore,
} from '@/store';
import SelectMenu from '@/elements/SelectMenu.vue';
import wall from '@/assets/image/bg.jpg';
interface Info {
avatar?: string;
account?: string;
}

const menuItems = ref([
{ label: '添加图标', value: 'addIcon' },
{ label: '编辑主页', value: 'editHome' },
]);
const contextMenuStore = useContextMenuStore();
function showContextMenu(event) {
contextMenuStore.setContextMenu(menuItems.value);
contextMenuStore.setPosition(event);
}
const settingStore = useSettingStore();
function getSetting() {
settingApi.get().then((res) => {
    if (res.backgroundPicture) {
    // 修改css变量属性
    document.documentElement.style.setProperty(
        '--bg-image',
        `url(${res.backgroundPicture})`
    );
    } else {
    document.documentElement.style.setProperty('--bg-image', `url(${wall})`);
    }
    // todo 处理其他设置
    settingStore.setSetting(res);
});
}
const userInfoStore = useUserInfoStore();
const getUser = () => {
loginApi.getUserInfo().then((res) => {
    userInfoStore.setUserInfo(res);
});
};
watchEffect(() => {
if (contextMenuStore.menuActive === 'editIcon') {
    showAddIconWeb();
    // contextMenuStore.setMenuActive("");
} else if (contextMenuStore.menuActive === 'editFolderIcon') {
    showAddIconWeb();
    // contextMenuStore.setMenuActive("");
}
});

watchEffect(() => {
    getSetting();
    getUser();
});
type SettingInstance = InstanceType<typeof Setting>;
const setting = ref<SettingInstance | null>(null);
const clickAvatar = () => {
setting.value.openModal();
};
const iconWebVisible = ref(false);

let currentPage = ref<number>(0);
let currentCate = ref<string>('');

provide('currentCate', currentCate);

const showAddIconWeb = () => {
    iconWebVisible.value = true;
};
const hideAddIconWeb = (event) => {
const ignoreElements = document.querySelectorAll('.side-box');
const menu = document.querySelectorAll('.select-menu');
const clipElements = document.querySelectorAll('.clip-container');
if (
    ![...ignoreElements, ...menu, ...clipElements].some((el) =>
    el.contains(event.target as Node)
    )
) {
    iconWebVisible.value = false;
}
};
type ViewListInstance = InstanceType<typeof ViewList>;
const viewList = ref<ViewListInstance | null>(null);
const addIcon = (item) => {
viewList.value.addIcon(item);
};
const editIcon = (item) => {
viewList.value.editIcon(item);
};
type SideBarInstance = InstanceType<typeof SideBar>;
const sideBar = ref<SideBarInstance | null>(null);

let scrollCount = 0;
let scrollTimeout;

function handleScroll(event) {
scrollCount++;
clearTimeout(scrollTimeout);

scrollTimeout = setTimeout(() => {
    scrollCount = 0;
}, 500);

if (scrollCount >= 3) {
    if (event.deltaY < 0) {
    currentPage.value === 0 ? '' : currentPage.value--;
    } else {
    const maxNum = sideBar.value.getTotalLength();
    currentPage.value < maxNum - 1 ? currentPage.value++ : '';
    }

    // 重置计数器
    scrollCount = 0;
}
}

const homeContainer = ref<HTMLElement | null>(null);
// 打开小组件弹窗
const templateVisible = ref(false as boolean) 
const addTemplate=()=>{
    templateVisible.value = true
    iconWebVisible.value=false
}
const addHomepageItem=ref({} as any)
// 添加小组件到主页
const addHomepage = (item) => {
    addHomepageItem.value=item
}
const changeActiveIndex=id=>{
    contextMenuStore.menuList?.forEach((item,index) => {
       if(item.id == id){
           currentPage.value=index
       }
    })
}
onMounted(() => {
homeContainer.value.addEventListener('wheel', handleScroll);
});

onUnmounted(() => {
homeContainer.value.removeEventListener('wheel', handleScroll);
});
</script>

<style scoped>
#app {
background: #000;
-webkit-user-drag: none;
}
.mask {
background-color: rgba(0, 0, 0, 0.1);
backdrop-filter: blur(0px);
pointer-events: none;
}
</style>
